package diploma.kisel.modelas.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import diploma.kisel.hibernate.util.HibernateUtil;
import diploma.kisel.modelas.domain.Device;
import diploma.kisel.modelas.domain.DeviceType;
import diploma.kisel.modelas.repository.api.DeviceRepository;

public class DeviceRepositoryImpl implements DeviceRepository {

	EntityManager em = HibernateUtil.getEm();

	@Override
	public List<Device> findAll() {
		List<Device> devices = em.createNamedQuery("Device.findAll",
				Device.class).getResultList();
		return devices;
	}

	@Override
	public List<Device> findByPrice(int minPrice, int maxPrice) {
		TypedQuery<Device> query = em.createNamedQuery("Device.findByPrice", Device.class);
		query.setParameter("minPrice", minPrice);
		query.setParameter("maxPrice", maxPrice);
		return query.getResultList();
	}

	@Override
	public Device save(Device device) {
		em.getTransaction().begin();
		em.persist(device);
		em.getTransaction().commit();
		return device;
	}

	@Override
	public Device update(Device device) {
		em.getTransaction().begin();
		em.merge(device);
		em.getTransaction().commit();
		return device;
	}

	@Override
	public void remove(Device device) {
		em.getTransaction().begin();
		em.remove(device);
		em.getTransaction().commit();
	}

	@Override
	public Device findById(int id) {
		TypedQuery<Device> query= em.createNamedQuery("Device.findById", Device.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	@Override
	public List<Device> findByPriceAndType(int minPrice, int maxPrice,
			DeviceType type) {
		TypedQuery<Device> query = em.createNamedQuery("Device.findByPriceAndType", Device.class);
		query.setParameter("minPrice", minPrice);
		query.setParameter("maxPrice", maxPrice);
		query.setParameter("type", type);
		return query.getResultList();
	}

}
